package com.the_last.controller;

import com.the_last.pojo.bo.LoginUser;
import com.the_last.pojo.dto.SubmitOrderDTO;
import com.the_last.pojo.po.Order;
import com.the_last.pojo.vo.OrderDetailVO;
import com.the_last.pojo.vo.OrderVO;
import com.the_last.pojo.vo.PageVO;
import com.the_last.service.OrderService;
import com.the_last.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    @PostMapping("/submit")
    @PreAuthorize("hasAuthority('ORDER_CREATE')")
    public Result<Order> submitOrder(
            @RequestBody SubmitOrderDTO submitOrderDTO,
            @AuthenticationPrincipal LoginUser loginUser) {
        return orderService.submitOrder(submitOrderDTO, loginUser.getUser().getId());
    }
    
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ORDER_QUERY')")
    public Result<PageVO<OrderVO>> getOrderList(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false, defaultValue = "-1") Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @AuthenticationPrincipal LoginUser loginUser) {
        // 根据权限决定查询范围：具有ORDER_QUERY权限的管理员可以查询所有订单，否则只能查询自己的订单
        Long actualUserId = userId;
        if (userId == null && loginUser.getAuthorities().stream()
                .noneMatch(authority -> "ORDER_MANAGE".equals(authority.getAuthority()))) {
            // 如果没有ORDER_QUERY权限且没有指定userId，则只能查询自己的订单
            actualUserId = loginUser.getUser().getId();
        }
        return orderService.getOrderList(actualUserId, status, pageNum, pageSize);
    }
    
    @PutMapping("/pay")
    public Result<String> payOrder(@RequestParam String orderId) {
        return orderService.payOrder(orderId);
    }
    
    @GetMapping("/{orderId}")
    @PreAuthorize("hasAuthority('ORDER_QUERY')")
    public Result<OrderDetailVO> getOrderDetail(@PathVariable String orderId) {
        return orderService.getOrderDetail(orderId);
    }
    
    /**
     * 删除订单
     *
     * @param orderId 订单ID
     * @return 删除结果
     */
    @DeleteMapping("/{orderId}")
    @PreAuthorize("hasAuthority('ORDER_DELETE')")
    public Result<String> deleteOrder(@PathVariable String orderId) {
        return orderService.deleteOrder(orderId);
    }
} 